import { createRouter, createWebHistory } from "vue-router";
import Layout from "@/views/layout/index.vue";
import { routerConponent } from "@/utils/routerMap";

const routes = [
  // {
  //   // path: "/",
  //   name: "/",
  //   redirect: "/",
  // },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/404",
    name: "404",
    component: () => import("@/views/404.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 需要过滤掉的路由
const filterRoutes = ["/login", "/404"];

// 路由拼接
function loadView(view) {
  // 路由映射对象
  return routerConponent[view];
}

// 路由过滤   遍历路由 转换为组件对象和路径
function filterASyncRoutes(data) {
  const routes = data.filter((item) => {
    // if (item["component"] === "Layout") item.component = Layout;
    // else item["component"] = loadView(item["component"]);
    item["component"] = loadView(item["component"]);
    // 路由递归，转换组件对象和路径
    if (item["children"] && item["children"].length > 0)
      item["children"] = filterASyncRoutes(item.children);
    return true;
  });
  return routes;
}

// 路由过滤和跳转
async function onFilterRoutes(to, next, e) {
  const routes = await filterASyncRoutes(e); // 路由过滤
  routes.sort((a, b) => a["id"] - b["id"]);
  routes.forEach((item) => {
    router.options.routes.push(item);
    router.addRoute(item);
  });
  next({ ...to, replace: true });
}

router.beforeEach(async (to, from, next) => {
  // 获取token和原始路由数组
  const userRouter = JSON.parse(sessionStorage.getItem("router"));
  const token = JSON.parse(sessionStorage.getItem("token"));

  // 判断路由指向是否在需要过滤的路由地址数组里
  // 如果在，则直接跳进页面，无需判断
  if (filterRoutes.indexOf(to.path) !== -1) {
    next();
    return false;
  }

  if (routes.length == 2) {
    // 当token和原始路由都存在的时候
    if (token && userRouter && userRouter.routes) {
      await onFilterRoutes(to, next, userRouter.routes); // 执行路由过滤和跳转
    } else next({ path: "/login", replace: true });
  } else next();
});

export default router;
